﻿using System;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace SunLine.Documents.Infrastructure.NHibernateMaps.Conventions
{
    /// <summary>
    /// Konwencja dla kolumn not nullable
    /// </summary>
    public class NotNullPropertyConvention : IPropertyConvention
    {
        /// <summary>
        /// Motoda do zastosowania konwencji NotNull
        /// </summary>
        /// <param name="instance"></param>
        public void Apply(IPropertyInstance instance)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");

            if (!IsNullableProperty(instance))
                instance.Not.Nullable();
        }

        private static bool IsNullableProperty(IPropertyInstance instance)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");

            var type = instance.Type;
            return (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) || type.Equals(typeof(string));
        }
    }
}
